<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>编辑角色</span>
        </div>
      </template>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        v-loading="loading"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="权限设置">
          <el-tree
            ref="permissionTree"
            :data="permissionTree"
            show-checkbox
            node-key="id"
            :default-checked-keys="defaultPermissions"
            :props="{ label: 'name', children: 'children' }"
          />
        </el-form-item>
        <el-form-item>
          <el-button v-test-account type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getRole, updateRole, getRolePermissions } from '@/api/role'
import { getPermissions } from '@/api/permission'

const router = useRouter()
const route = useRoute()
const roleId = route.params.id

const formRef = ref(null)
const loading = ref(false)
const permissionTree = ref([])
const permissionTreeRef = ref(null)
const defaultPermissions = ref([])

const form = reactive({
  id: undefined,
  name: '',
  description: '',
  permissions: []
})

const rules = {
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
}

// 获取角色详情
const getRoleDetail = async () => {
  loading.value = true
  try {
    // 获取角色基本信息
    const roleResponse = await getRole(roleId)
    if (roleResponse.data) {
      form.id = roleResponse.data.id
      form.name = roleResponse.data.name
      form.description = roleResponse.data.description
    }
    
    // 获取角色权限
    const permissionResponse = await getRolePermissions(roleId)
    defaultPermissions.value = permissionResponse.data || []
    
  } catch (error) {
    console.error('获取角色详情失败', error)
    ElMessage.error('获取角色详情失败')
  } finally {
    loading.value = false
  }
}

// 获取权限树
const getPermissionTree = async () => {
  try {
    const response = await getPermissions()
    permissionTree.value = response.data || []
  } catch (error) {
    console.error('获取权限列表失败', error)
    ElMessage.error('获取权限列表失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  // 表单验证
  try {
    await formRef.value.validate()
    
    // 获取选中的权限
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]
    
    form.permissions = allCheckedKeys
    
    // 更新角色
    await updateRole(form.id, form)
    ElMessage.success('更新成功')
    
    // 返回角色列表
    goBack()
  } catch (error) {
    console.error('更新角色失败', error)
    ElMessage.error('更新角色失败')
  }
}

// 返回上一页
const goBack = () => {
  router.push('/system/roles')
}

// 页面加载时获取数据
onMounted(async () => {
  await getPermissionTree()
  await getRoleDetail()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 